package com.zxyankh.leetcode.question.chinese;

import java.util.ArrayList;
import java.util.List;

/**
 * 给定两个以字符串形式表示的非负整数 num1 和 num2，返回 num1 和 num2 的乘积，它们的乘积也表示为字符串形式。
 * <p>
 * 示例 1:
 * <p>
 * 输入: num1 = "2", num2 = "3"
 * 输出: "6"
 * 示例 2:
 * <p>
 * 输入: num1 = "123", num2 = "456"
 * 输出: "56088"
 * 说明：
 * <p>
 * num1 和 num2 的长度小于110。
 * num1 和 num2 只包含数字 0-9。
 * num1 和 num2 均不以零开头，除非是数字 0 本身。
 * 不能使用任何标准库的大数类型（比如 BigInteger）或直接将输入转换为整数来处理。
 *
 * @author zxyAnkh
 */
public class No43 {

    public static void main(String[] args) {
        No43 no43 = new No43();
        System.out.println(no43.multiply("2", "3"));
        System.out.println(no43.multiply("12", "3"));
        System.out.println(no43.multiply("2", "31"));
        System.out.println(no43.multiply("20", "31"));
        System.out.println(no43.multiply("123", "31"));
        System.out.println(no43.multiply("123", "456"));
        System.out.println(no43.multiply("9130", "0"));
    }


    public String multiply(String num1, String num2) {
        StringBuilder stringBuilder = new StringBuilder();

        List<String> list = new ArrayList<>();
        int m = 0;

        int a;
        for (int i = num1.length() - 1; i > -1; i--) {
            a = 0;
            for (int j = num2.length() - 1; j > -1; j--) {
                int b = (num1.charAt(i) - '0') * (num2.charAt(j) - '0') + a;
                a = b / 10;
                stringBuilder.append(b % 10);
            }
            if (a != 0) {
                stringBuilder.append(a);
            }
            stringBuilder.reverse();
            for (int k = 0; k < num1.length() - i - 1; k++) {
                stringBuilder.append('0');
            }
            if (m < stringBuilder.length()) {
                m = stringBuilder.length();
            }
            list.add(stringBuilder.toString());
            stringBuilder.delete(0, stringBuilder.length());
        }

        a = 0;
        for (int i = 0; i < m; i++) {
            int sum = 0;
            for (String s : list) {
                if (s.length() > i) {
                    sum += (s.charAt(s.length() - i - 1) - '0');
                }
            }
            sum += a;
            a = sum / 10;
            sum = sum % 10;
            stringBuilder.append(sum);
        }
        if (a > 0) {
            stringBuilder.append(a);
        }
        boolean zero = true;
        for (int i = 0; i < stringBuilder.length(); i++) {
            if (stringBuilder.charAt(i) != '0') {
                zero = false;
            }
        }

        if (zero) {
            return "0";
        }
        return stringBuilder.reverse().toString();
    }

}
